var express = require("express");
    consolidate = require("consolidate");
    path = require("path");
    mysql = require("mysql");
    bodyParser = require("body-parser");
    session = require("express-session");

var app = express();


app.use(session({
    name: 'current_admin',
    secret: 'cnjd-student-manage-system',
    rolling: true,
    resave:true,
    saveUninitialized:true,
    cookie:{
        maxAge: 180000 // 或者 1000 * 60 * 30
    }
}));


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended:false }));

// parse application/json
app.use(bodyParser.json());

app.set("views", path.resolve(__dirname, "views")); // 模板位置
app.set('view engine', 'html'); // 设置把模板以html形式输出
app.engine('html', consolidate.swig);

var pool = mysql.createPool({
    host:'127.0.0.1',
    user:'root',
    password:'root',
    database:'cnjd-student-manage-system'
});

app.post("/api/login",function(req, res, next){
    console.log(req.body);
    var login_acco = req.body.login_acco;
    var login_password = req.body.login_password;
    if(login_acco && login_password){
        // 查询数据库
        pool.query(
            'SELECT * FROM t_admin WHERE login_acco = ? AND login_password = ?',
            [login_acco, login_password],
            function(error, results, fileds){
                if(error) throw error;
                // console.log('results:' + results);
                if(results.length > 0) {
                    var admin = results[0];
                    req.session.current_admin = admin;
                    res.json({code:1, msg:'登录成功！', data: results[0]});
                }else {
                    res.json({code:-1, msg:'账号或密码错误！', data: null});
                };
            }
        );
    }else {
        res.json({code:-1, msg:'参数非法', data: null});
    };
});

app.post('/api/students', function(req, res, next) {
    pool.query('SELECT * FROM t_student', function(error, results, fields) {
        if(error) throw error;
        res.json({code: 1, msg:"查询成功！", data: results});
    });
});

app.post('/api/student_insert',function(req, res, next) {
    // console.log(req.body.sex);
    pool.query('INSERT t_student(name, sex, age, no, class_name) VALUES(?, ?, ?, ?, ?)', [
        req.body.name,
        req.body.sex,
        req.body.age,
        req.body.no,
        req.body.class_name
    ],function(error, results, fields) {
        console.log(results);
        if(error) throw error;
        if(results.affectedRows === 1){
            res.json({code:1, msg:'添加成功！', data:null});
        } else {
            res.json({code:-1, msg:'添加失败！', data:null});
        }
    });
});

app.post('/api/student_updata', function(req, res, next) {
    // console.log(req.body);
    pool.query('UPDATE t_student SET name = ?, sex = ?, age = ?, no = ?, class_name = ? WHERE id = ?',[
        req.body.name,
        req.body.sex,
        req.body.age,
        req.body.no,
        req.body.class_name,
        req.body.id
    ], function(error, results, fields) {
        if(error) throw error;
        if(results.affectedRows === 1){
            res.json({code:1, msg:'添加成功！', data:null});
        } else {
            res.json({code:-1, msg:'添加失败！', data:null});
        }
    });
});

//delete
app.post("/api/student_delete", function(req, res, next) {
    var id = req.body.id;
    if (id) {
        pool.query('DELETE FROM t_student WHERE id = ?', [
            id
        ], function(error, results, fields) {
            if(error) throw error;
            if (results.affectedRows === 1) {
                res.json({code: 1, msg:"删除成功！", data: null});
            }else{
                res.json({code: -1, msg:"删除失败！", data: null});
            }
        });
    } else {
        res.json({code: -1, msg:"参数非法！", data: null});
    }
});

// 修改学生
app.get("/student_updata", function(req, res, next) {
    pool.query('SELECT * FROM t_student WHERE id = ?',[
        req.query.id
    ],function(error, results, fields){
        if(error) throw error;
        res.render('student_updata', { student: results[0] });
    });
});

// 添加学生
app.get("/student_insert", function(req, res, next) {
    res.render('student_insert');
});

// 学生列表
app.get("/students", function(req, res, next) {
    if (req.session.current_admin) {
        res.render('students');
    } else {
        res.redirect('/');
    }
});

// 退出登录
app.get('/logout', function(req, res, next) {
    delete req.session.current_admin
    res.redirect('/');
});

app.get("/", function(req, res, next) {
    if (req.session.current_admin) {
        res.redirect('/students');
    } else {
        res.render('login');
    }
});

app.listen(8080, function() {
    console.log('app listening at 8080.');
});












































